package com.oig.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.lang.NonNull;

import java.util.List;
import java.util.Map;

/**
 * alibaba fastjson 工具类
 */
public class JsonUtil {


	private JsonUtil(){}

	/**
	 * 对象转换成json字符串
	 */
	public static String toJSONString(@NonNull Object obj) {
		return JSONObject.toJSONString(obj,
				SerializerFeature.QuoteFieldNames,
				SerializerFeature.WriteMapNullValue,
				SerializerFeature.WriteNullListAsEmpty,
				SerializerFeature.WriteNullStringAsEmpty,
				SerializerFeature.WriteNonStringValueAsString,
				SerializerFeature.WriteNullBooleanAsFalse,
				SerializerFeature.WriteDateUseDateFormat);
	}


	/**
	 * json字符串转对象
	 */
	public static <T> T toObject(@NonNull String jsonStr, @NonNull Class<T> tClass){
		JSONObject jsonObject = JSONObject.parseObject(jsonStr);
		return JSON.toJavaObject(jsonObject, tClass);
	}


	/**
	 * 转换为数组
	 */
	public static <T> Object[] toArray(@NonNull String text, @NonNull Class<T> clazz) {
		return JSON.parseArray(text, clazz).toArray();
	}

	/**
	 * 转换为List
	 */
	public static <T> List<T> toList(@NonNull String text, @NonNull Class<T> clazz) {
		return JSON.parseArray(text, clazz);
	}

	/**
	 * json字符串转化为map
	 */
	public static Map<String,Object> stringToCollect(@NonNull String s) {
		return JSONObject.parseObject(s);
	}

	/**
	 * 将map转化为string
	 */
	public static String collectToString(@NonNull Map<String,Object> m) {
		return JSONObject.toJSONString(m);
	}

}
